package com.haoshuang.zhouzhoubang.ui.page.order.take.services.detail

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityChooseServiceDetailBinding
import com.haoshuang.zhouzhoubang.model.bean.AttrBean2
import com.haoshuang.zhouzhoubang.model.bean.DetailFBean
import com.haoshuang.zhouzhoubang.model.bean.ShoppingBannerBean
import com.haoshuang.zhouzhoubang.ui.adapter.BzAdapter
import com.haoshuang.zhouzhoubang.ui.adapter.ImageAdapter3
import com.haoshuang.zhouzhoubang.ui.adapter.ServiceAdapter
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.visible
import java.text.DecimalFormat

/**
 *  选择服务的详情页面
 */
class ChooseServiceDetailActivity :
    BaseVMActivity<ChooseServiceDetailViewModel, ActivityChooseServiceDetailBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<ChooseServiceDetailActivity>()
        }
    }

    private var ids = 0

    // 是否是套餐
    private var topIsMeal = 0
    // 接口请求地址

    var list3 = arrayListOf<String>()
    lateinit var adapter3: BzAdapter
    lateinit var adapter4: ServiceLabelAdapter4
    var bean: DetailFBean? = null
    var list8 = arrayListOf<AttrBean2>()
    // 当前选中的价格
    var price2 = "0"
    var price3 = "0"
    var price4 = "0"
    private var url = "/api/store_api/get_spread_product_detail"
    override fun initIntent() {
        ids = intent.getIntExtra("ids", 0)
        topIsMeal = intent.getIntExtra("topIsMeal", 0)
        url =
            if (topIsMeal == 1) "/api/store_api/get_spread_meal_detail" else "/api/store_api/get_spread_product_detail"
    }


    override fun initView(savedInstanceState: Bundle?) {
        binding.titleBar.title = "服务详情"
        binding.titleBar.leftImageView().click { finish() }
        adapter3 = BzAdapter(list3)
        adapter4 = ServiceLabelAdapter4(list8)
        initBanner()
        val lay = LinearLayoutManager(this@ChooseServiceDetailActivity)
        val lay3 = LinearLayoutManager(this@ChooseServiceDetailActivity)
        lay3.orientation = LinearLayoutManager.HORIZONTAL
        lay.orientation = LinearLayoutManager.HORIZONTAL

        binding.apply {
            val flexboxLayoutManager1 = FlexboxLayoutManager(mActivity)
            flexboxLayoutManager1.flexDirection = FlexDirection.ROW
            flexboxLayoutManager1.flexWrap = FlexWrap.WRAP   //按正常方向换行
            flexboxLayoutManager1.justifyContent = JustifyContent.FLEX_START //交叉轴的起点对齐。
            rvGg.layoutManager = flexboxLayoutManager1
            rvGg.adapter = adapter4
            adapter4.setOnItemClick { view, position, _ ->
                if (list8[position].isCheck == 0) {
                    for (b in list8) {
                        b.isCheck = 0
                    }
                    list8[position].isCheck = 1
                    price2 = list8[position].price
                    tvPrice.text = price2
                    tvPrice1.text = "¥" + list8[position].cost
                } else {
                    price2 = price3
                    tvPrice.text = price3
                    tvPrice1.text = "¥" + price4
                    list8[position].isCheck = 0
                }
                adapter4.notifyDataSetChanged()
            }

            llConfirm.clickWithTrigger {
                // 服务id
                val id = bean?.detail?.id
                // 服务名称
                val name = bean?.detail?.store_name
                // 服务规格
                val spec = list8.firstOrNull { it.isCheck == 1 }
                val suk = spec?.suk ?: ""
                // 服务价格
                val price = price2

                val image = bean?.detail?.slider_image?.firstOrNull() ?: ""

                if (bean?.detail?.key_areas.isNullOrEmpty()){
                    setResult(200, Intent().apply {
                        putExtra("id", id.toString())
                        putExtra("name", name)
                        putExtra("spec", suk)
                        putExtra("price", price)
                        putExtra("image", image)
                    })
                    finish()
                }else{
                    XPopup.Builder(mActivity)
                        .asBottomList("请选择重点区域", bean?.detail?.key_areas!!.toTypedArray()){position,text ->
                            setResult(200, Intent().apply {
                                putExtra("id", id.toString())
                                putExtra("name", name)
                                putExtra("spec", suk)
                                putExtra("price", price)
                                putExtra("image", image)
                                putExtra("key_areas", text)
                            })
                            finish()
                        }
                        .show()
                }


            }
            rvBz.layoutManager = lay3
            rvBz.adapter = adapter3
        }
    }

    private fun initBanner() {
        //设置xbanner的图片点击事件
        binding.banner.setOnItemClickListener { xBanner, model, view, position ->
        }
        //设置xbanner加载图片
        binding.banner.loadImage { xBanner, model, view, position ->
            model as ShoppingBannerBean // 此处的model无法自动识别，因此需要手动将其转换成setBannerData的参数中的数据类型
            //在此处使用图片加载框架Glide加载图片
            Glide.with(this)
                .load(model.url)
                .placeholder(R.mipmap.default_image)
                .error(R.mipmap.default_image)
                .into(view as ImageView)
        }
    }


    override fun initData() {
        vm.getData(url, "id" to ids, "area_id" to AccountUtils.user?.area_id)
    }

    override fun startObserve() {
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    binding.apply {
                        bean = it
                        var list5 = bean!!.detail.slider_image;
                        val bannerFreshData = mutableListOf<ShoppingBannerBean>()

                        for (i in list5.indices) bannerFreshData.add(
                            ShoppingBannerBean(
                                list5[i],
                                "商品图片${i}"
                            )
                        )

                        //刷新数据之后，需要重新设置是否支持自动轮播，通过判断图片数据列表的大小来决定
                        binding.banner.setAutoPlayAble(bannerFreshData.size > 1)
                        binding.banner.setBannerData(bannerFreshData)
                        try {
                            var bean = it.detail.attr
                            tvName.text = bean.name
                            list8.addAll(bean.data)
                            list8[0].isCheck = 1
                            adapter4.notifyDataSetChanged()
                        } catch (e: Exception) {

                        }
                        price2 = it.detail.price
                        price3 = it.detail.price
                        price4 = it.detail.ot_price
                        if (it.detail.is_seckill == 0) {
                            vLine.visible()
                            storeName.text = it.detail.store_name
                            tvPrice.text = it.detail.price
                            tvPrice1.text = "¥" + it.detail.ot_price
                            storeName2.text = it.detail.pro_descript
                            tvPrice1.setPaintFlags(tvPrice1.getPaintFlags() or Paint.STRIKE_THRU_TEXT_FLAG)

                        } else {
                            vLine.gone()
                        }

                        list3.addAll(it.guarantee_title)
                        adapter3.notifyDataSetChanged()
                    }
                }
            }
        }
    }
}